# Deleting Paperclip Attachments with ActiveAdmin

This technique will be consistent with the underlying mechanism used by Rails' built-in nested attributes for associations. 

This example will use an `Author` model with an existing `avatar` attachment that we want to be able to delete in ActiveAdmin:

```rb
class Author < ApplicationRecord
  ...
  has_attached_file :avatar
  ...
end
```

## Step 1: Add `<attachment_name>_attributes=` writer method

As `accepts_nested_attributes_for` only works with ActiveRecord associations like `has_one`, `has_many`, etc. we will not make direct use of it, but manually add the writer method it generates itself.

_(To understand how nested attributes work in Rails see http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html)._

Add a `<attachment_name>_attributes=` writer method like below to your model that already uses `has_attached_file`:

```diff
class Author < ApplicationRecord
  ...
  has_attached_file :avatar

+ def avatar_attributes=(attributes)
+   # Marks the attachment for destruction on next save,
+   # if the attributes hash contains a _destroy flag
+   # and a new avatar was not uploaded at the same time:
+   avatar.clear if has_destroy_flag?(attributes) && !avatar.dirty?
+ end
end
```

The method calls `Paperclip::Attachment#clear` to mark the attachment for destruction when the model is next saved.

## Step 2: Setup ActiveAdmin strong params

Open `app/admin/authors.rb` (use the correct file path for your app) and setup strong parameters to permit the `_destroy` flag nested attribute:

```diff
# File: app/admin/authors.rb
ActiveAdmin.register Author do

-  permit_params :name, :bio, :avatar
+  permit_params :name, :bio, :avatar, avatar_attributes: [:_destroy]

```

## Step 3: Add nested `_destroy` checkbox to ActiveAdmin form

In `app/admin/authors.rb` setup the `form` block to include a `_destroy` checkbox. This checkbox must be nested within `<attachment_name>_attributes` using `semantic_fields_for` (or one of the other nested attributes methods provided by formtastic).

```diff
  form do |f|
    f.semantic_errors
    f.inputs do
      f.input :name
      f.input :bio
      f.input :avatar, as: :file
+     if f.object.avatar.present?
+       f.semantic_fields_for :avatar_attributes do |avatar_fields|
+         avatar_fields.input :_destroy, as: :boolean, label: 'Delete?'
+       end
+     end
    end
    f.actions
  end
```

Your form should now show a delete checkbox when there is an attachment present. Checking this checkbox and submitting a valid form ought to delete the attachment.